const webSocket = require("ws")
const path = require('path')
const fileUtils = require('../utils/fileReader')

const wss = new webSocket.Server({
    port: 3001
})
module.exports.listen = function () {
    wss.on("connection", client => {
        console.log("有客户端连接了");
        client.on("message", async msg => {
            console.log("客户端发送数据过来了" + msg);
            let payload = JSON.parse(msg)
            if (payload.action === 'getData') {
                // 返回每个模块的数据
                let filePath = '../data/' + payload.chartName + '.json'
                filePath = path.join(__dirname, filePath)
                const ret = await fileUtils.getFileJsonData(filePath)
                payload.data = ret // 增加data字段
                client.send(JSON.stringify(payload))
            } else {
                // 主题切换, 全屏切换, 进行每个客户端的同步, 收到什么数据就发送什么数据
                wss.clients.forEach(client => {
                    client.send(JSON.stringify(payload))
                })
            }

        })
    })
}